#include "socketfilepair.h"

void initialize_SocketFilePair(SocketFilePair *sF, const char *file, const int socket, int *socketPair)
{

  if(sF != NULL)
    {
      if(file != NULL)
	{
	  sF->file = (char *) malloc ((strlen(file) + 1) * sizeof(char));
	  if(sF->file == NULL)
	    {
	      fprintf(stderr, "[initialize_SocketFilePair]Erreur malloc plus de place disponible\n");
	      exit(1);
	    }
	  strcpy(sF->file, file);
	}
      else
	sF->file = NULL;
      sF->socket = socket;
      if(socketPair != NULL)
	{
	  sF->socketPair = socketPair;
	}
      else
	sF->socketPair = NULL;
    }
}

void create_SocketFilePair(Element *sFDest, const Element sFSrc)
{
  SocketFilePair *sSrc = (SocketFilePair *)sFSrc;
  if(sFSrc == NULL)
    {
      (*sFDest) = NULL;
      return;
    }
  (*sFDest) = (SocketFilePair *) malloc (sizeof(SocketFilePair));
  initialize_SocketFilePair((*sFDest), sSrc->file, sSrc->socket, sSrc->socketPair);
}

void testament_SocketFilePair(SocketFilePair *sF)
{
  if(sF)
    {
      if(sF->file)
	{
	  free(sF->file);
	}
      sF->socket = -1;
      if(sF->socketPair)
	sF->socketPair = NULL;
    }
}

void delete_SocketFilePair(Element *sF)
{
  SocketFilePair **s = (SocketFilePair **) sF;
  if((*s) != NULL)
    {
      testament_SocketFilePair((*s));
      free((*s));
      (*s) = NULL;
    }
}

ListReturn compare_SocketFilePair(Element sFA, Element sFB)
{
  SocketFilePair *sA = (SocketFilePair *) sFA;
  SocketFilePair *sB = (SocketFilePair *) sFB;
  if(sA == sB)
    return LIST_COMP_EQ;
  if(sA == NULL || sB == NULL)
    return LIST_COMP_DIF;
  if(sA->file == NULL || sB->file == NULL)
    {
      /* Comparaison sur la socket */
      if(sA->socket == sB->socket)
	return LIST_COMP_EQ;
    }
  else if(sA->socket == -1 || sB->socket == -1)
    {
      /* Comparaison sur le fichier */
      if(strcmp(sA->file, sB->file) == 0)
	return LIST_COMP_EQ;
    }
  else
    {
      if(strcmp(sA->file, sB->file) == 0 && sA->socket != sB->socket)
	return LIST_COMP_EQ;
      /* Comparaison sur les deux */
    }
  return LIST_COMP_DIF;
}
